package com.briup.common.config;

import com.briup.common.properties.UploadConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 本地上传的配置类
 */
@Slf4j
@ConditionalOnProperty("briup.config.upload.bast-path")
@Configuration
public class WebLocalUploadPathAutoConfig implements WebMvcConfigurer {

	@Autowired
	private UploadConfigProperties localUploadConfigProperties;


	/**
	 * 配置上传路径
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		String localUploadBastPath = localUploadConfigProperties.getBastPath();

		if(localUploadBastPath == null || "".equals(localUploadBastPath)){
			String filePath = WebLocalUploadPathAutoConfig.class.getClassLoader().getResource("").getPath();
			if(filePath.indexOf(".jar")>0){
				filePath = filePath.substring(0, filePath.indexOf(".jar"));
			}else if(filePath.indexOf("classes")>0){
				filePath = "file:"+filePath.substring(0, filePath.indexOf("classes"));
			}
			filePath = filePath.substring(0, filePath.lastIndexOf("/"))+"/images/";
			localUploadBastPath = filePath;
		}
		log.info("文件本地上传路径为 : local-upload-bast-path = "+ localUploadBastPath);

		//注意如果是项目外部的资源需要加file:
		registry.addResourceHandler("/static/**/").addResourceLocations(localUploadBastPath);
		registry.addResourceHandler("/static/**/").addResourceLocations("file:"+localUploadBastPath);
	}

}
